package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.config.AliPay;
import com.ruoyi.system.config.AliPayController;
import com.ruoyi.system.config.Total;
import com.ruoyi.system.config.VheicleReport;
import com.ruoyi.system.domain.DsStoragemanagement;
import com.ruoyi.system.service.IDsStoragemanagementService;
import com.ruoyi.system.util.AmountCalculation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 出入库管理Controller
 *
 * @author ruoyi
 * @date 2024-07-08
 */
@RestController
@RequestMapping("/system/storagemanagement")
public class DsStoragemanagementController extends BaseController {
    @Autowired
    private IDsStoragemanagementService dsStoragemanagementService;
    @Autowired
    AliPayController aliPayController;


    /**
     * 查询出入库管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:storagemanagement:list')")
    @GetMapping("/list")
    public TableDataInfo list(DsStoragemanagement dsStoragemanagement) {
        startPage();
        List<DsStoragemanagement> list = dsStoragemanagementService.selectDsStoragemanagementList(dsStoragemanagement);
        System.out.println("测试接口的数据" + list);
        return getDataTable(list);
    }

    /**
     * 导出出入库管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:storagemanagement:export')")
    @Log(title = "出入库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DsStoragemanagement dsStoragemanagement) {
        List<DsStoragemanagement> list = dsStoragemanagementService.selectDsStoragemanagementList(dsStoragemanagement);
        ExcelUtil<DsStoragemanagement> util = new ExcelUtil<DsStoragemanagement>(DsStoragemanagement.class);
        util.exportExcel(response, list, "出入库管理数据");
    }

    /**
     * 获取出入库管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:storagemanagement:query')")
    @GetMapping(value = "/query")
    public AjaxResult getInfo(DsStoragemanagement dsStoragemanagement, HttpServletResponse httpResponse) throws Exception {
        System.out.println(dsStoragemanagement.getStorageId());
        DsStoragemanagement sd = dsStoragemanagementService.selectDsStoragemanagementByStorageId(dsStoragemanagement);
        System.out.println(sd.getStorageDateTime());
        AmountCalculation amoun = new AmountCalculation();
        System.out.println("入库时间" + sd.getStorageDateTime());
        System.out.println("出库时间" + sd.getDeliveryDateTime());
//        List jiner = amoun.jiner(sd.getStorageDateTime(), sd.getDeliveryDateTime());
//        sd.setStoptime(jiner.get(0).toString());
//        AliPay aliPay = new AliPay();
//        aliPay.setTraceNo(sd.getRnumber());
//        aliPay.setTotalAmount(sd.getAmount());
//        aliPay.setSubject(sd.getVehicleInfo());
//        aliPayController.pay(aliPay, httpResponse);
//        System.out.println(jiner);
        return success(sd);
    }

    /**
     * 新增出入库管理
     */
    @PreAuthorize("@ss.hasPermi('system:storagemanagement:add')")
    @Log(title = "出入库管理")
    @PostMapping
    public AjaxResult add(@RequestBody String Licenseplate) {//传车牌号过来
        int colonIndex = Licenseplate.indexOf(":");
        if (colonIndex == -1) {
            System.out.println("未找到':'分隔符");
        }
        // 找到":"后第一个双引号的位置，即值的开始位置（跳过冒号和第一个双引号）
        int startIndex = Licenseplate.indexOf("\"", colonIndex + 1);
        if (startIndex == -1) {
            System.out.println("未找到值开始的双引号");
        }
        // 找到值结束的双引号的位置
        int endIndex = Licenseplate.indexOf("\"", startIndex + 1);
        if (endIndex == -1) {
            System.out.println("未找到值结束的双引号");
        }
        // 截取并打印值（从startIndex+1开始，到endIndex结束）
        String licensePlate = Licenseplate.substring(startIndex + 1, endIndex);
        System.out.println("车牌号为：" + licensePlate);
        long pduanid = dsStoragemanagementService.getselectIDSoto(licensePlate);//查询车俩是否已入库
        if (pduanid == 0) {
            long vehicleId;
            int mation = getVehicleinformation(licensePlate);//查看是否为会员用户
            int erinfo = getVehicleownerinfo(licensePlate);//查看是否为固定业主
            if (mation != 0) {
                vehicleId = getCharacters(mation, 1);
            } else if (erinfo != 0) {
                vehicleId = getCharacters(erinfo, 2);
            } else {
                vehicleId = getLingShi(0, 0);//添加为临时用户
            }
            DsStoragemanagement ds = new DsStoragemanagement();
            ds.setVehicleId(vehicleId);//角色id
            ds.setLicenseplate(licensePlate);//车牌号
            return toAjax(dsStoragemanagementService.insertDsStoragemanagement(ds));
        } else {
            DsStoragemanagement dsime = new DsStoragemanagement();
            dsime.setStorageId(pduanid);
            dsime = dsStoragemanagementService.selectDsStoragemanagementByStorageId(dsime);
            LocalDateTime now = LocalDateTime.now();
            // 假设我们使用系统默认时区
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zdt = now.atZone(zoneId);
            Date date = Date.from(zdt.toInstant());
            // 假设 dsStor 是一个对象，并且有一个 setDeliveryDateTime 方法接受 Date 类
            dsime.setDeliveryDateTime(date);//出库时间
            long jiner=0;
            int mation = getVehicleinformation(licensePlate);//查看是否为会员用户
            int erinfo = getVehicleownerinfo(licensePlate);//查看是否为固定业主
            if (mation == 0&&erinfo==0) {
                jiner = AmountCalculation.jiner(dsime.getStorageDateTime(), dsime.getDeliveryDateTime());//计算金额
            }
            String randomString = generateRandomString(21);
            dsime.setOrdernumber(randomString);//订单号
                dsime.setAmount(jiner);
                long i = 1;
                dsime.setOperationType(i);
                int ida = dsStoragemanagementService.updateDsStoragemanagement(dsime);
                return toAjax(ida);
        }
    }

    /**
     * 修改出入库管理
     */
    @PreAuthorize("@ss.hasPermi('system:storagemanagement:edit')")
    @Log(title = "出入库管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DsStoragemanagement dsStoragemanagement) {
        return toAjax(dsStoragemanagementService.updateDsStoragemanagement(dsStoragemanagement));
    }

    /**
     * 删除出入库管理
     */
    @PreAuthorize("@ss.hasPermi('system:storagemanagement:remove')")
    @Log(title = "出入库管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{storageIds}")
    public AjaxResult remove(@PathVariable Long[] storageIds) {
        return toAjax(dsStoragemanagementService.deleteDsStoragemanagementByStorageIds(storageIds));
    }
    @PreAuthorize("@ss.hasPermi('system:storagemanagement:vheicle')")
    @PostMapping("/vheicle")
    public AjaxResult vheicle(@RequestBody String query) {
        List list=new ArrayList();
        if (query==null||query==""){
            query="2024";
        }
        List<Total> listlingshi = dsStoragemanagementService.getvheicle(query,0);
        List<Total> listhuiyuan= dsStoragemanagementService.getvheicle(query,2);
        List<Total> listguding = dsStoragemanagementService.getvheicle(query,1);
        VheicleReport vhe1=new VheicleReport();
        vhe1.setName("临时车俩");
        vhe1.setType("line");
        vhe1.setStack("Totala");
        vhe1.setData(listlingshi);
        VheicleReport vhe2=new VheicleReport();
        vhe2.setName("会员车俩");
        vhe2.setType("line");
        vhe2.setStack("Totalb");
        vhe2.setData(listhuiyuan);
        VheicleReport vhe3=new VheicleReport();
        vhe3.setName("固定车俩");
        vhe3.setType("line");
        vhe3.setStack("Totalc");
        vhe3.setData(listguding);
        list.add(vhe1);
        list.add(vhe2);
        list.add(vhe3);
        System.out.println("测试接口的数据" + list);
        return success(list);
    }

    public int getVehicleinformation(String vehicleInfo) {
        return dsStoragemanagementService.getVehicleinformation(vehicleInfo);
    }

    public int getVehicleownerinfo(String vehicleInfo) {
        return dsStoragemanagementService.getVehicleownerinfo(vehicleInfo);
    }

    public int getCharacters(int id, int mid) {
        return dsStoragemanagementService.getCharacters(id, mid);
    }

    public int getLingShi(int id, int biao) {
        return dsStoragemanagementService.getLingShi(id, biao);
    }

    public static String generateRandomString(int length) {
        String charPool = "0123456789";
        StringBuilder sb = new StringBuilder();
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(charPool.length());
            sb.append(charPool.charAt(index));
        }
        return sb.toString();
    }
}